package com.kangfu.wechat.api;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kangfu.common.exception.BusinessException;
import com.kangfu.wechat.bean.result.OpenidRes;
import com.kangfu.wechat.utils.JsonUtil;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginApi extends BaseApi {
    private static final Logger logger = LoggerFactory.getLogger(LoginApi.class);

    public static OpenidRes getOpenID(String appid, String secret, String jsCode) {
        //拼接url
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("grant_type","authorization_code");
        map.put("appid",appid);
        map.put("secret",secret);
        map.put("js_code",jsCode);
        String url = BaseApi.parseParams(BaseApi.BASE_URI + "/sns/jscode2session", map);

        OkHttpClient okHttpClient = new OkHttpClient(); // 创建OkHttpClient对象
        Request request = new Request.Builder().url(url).build(); // 创建一个请求
        try {
            Response response = okHttpClient.newCall(request).execute(); // 返回实体
            if (response.isSuccessful()) { // 判断是否成功
                String string = response.body().string();
                logger.info("获取用户openid response: " + string);
                OpenidRes openidRes = JsonUtil.parseObject(string, OpenidRes.class);
                if (openidRes == null) {
                    throw new BusinessException("获取用户openid 失败");
                }
                return openidRes;
            }else {
                logger.error("获取用户openid 失败 : code : " + response.code() + " || message : " + response.message()) ;
                throw new BusinessException("获取用户openid 失败");
            }
        } catch (IOException e) {
            logger.error("获取用户openid 失败 : " + e.getMessage());
            throw new BusinessException("获取用户openid 失败");
        }
    }


}
